package com.dennytech.tac.utils.db;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.database.Cursor;
import android.text.TextUtils;

import com.dennytech.tac.model.Attraction;

/**
 * Attraction local database
 * 
 * @deprecated from 2012.10.17, now load data from api
 *  
 * @author jun.deng
 *
 */
@Deprecated
public class AttractionDBHelper extends DBHelper<Attraction> {

	private static AttractionDBHelper instance;

	public static AttractionDBHelper instance() {
		return instance;
	}

	public static void init(Context c) {
		if (instance == null) {
			instance = new AttractionDBHelper(c);
		}
	}

	private AttractionDBHelper(Context c) {
		super(c, "ta");
	}

	@Override
	public List<Attraction> query() {
		List<Attraction> taList = new ArrayList<Attraction>();
		try {
			String query = "SELECT * FROM " + tableName + " ORDER BY id;";
			Cursor c = db.rawQuery(query, null);
			if (c.moveToFirst()) {
				do {
					Attraction ta = new Attraction();
					ta.setId(c.getInt(0));
					ta.setType(c.getInt(1));
					ta.setHot(c.getInt(2));
					ta.setName(c.getString(3));
					ta.setIntro(c.getString(4));
					ta.setDetail(c.getString(5));
					ta.setPhotoUrl(c.getString(6));
					ta.setTel(c.getString(7));
					ta.setAddress(c.getString(8));
					ta.setLatitude(c.getDouble(9));
					ta.setLongitude(c.getDouble(10));
					taList.add(ta);

				} while (c.moveToNext());
				c.close();
			} else {
				c.close();
				return null;
			}
		} catch (Exception e) {
			return null;
		}
		return taList;
	}

	public List<Attraction> query(String keyword) {
		List<Attraction> taList = query();
		String trimKey = keyword.trim();

		if (TextUtils.isEmpty(trimKey)) {
			return taList;
		}

		List<Attraction> result = new ArrayList<Attraction>();
		for (Attraction ta : taList) {
			if (ta.getName() != null && ta.getName().contains(trimKey)) {
				result.add(ta);
			}
		}

		return result;
	}

	public Attraction query(int id) {
		Attraction ta = null;
		try {
			String query = "SELECT * FROM " + tableName + " WHERE id = " + id
					+ ";";
			Cursor c = db.rawQuery(query, null);
			if (c.moveToFirst()) {
				ta = new Attraction();
				ta.setId(c.getInt(0));
				ta.setType(c.getInt(1));
				ta.setHot(c.getInt(2));
				ta.setName(c.getString(3));
				ta.setIntro(c.getString(4));
				ta.setDetail(c.getString(5));
				ta.setPhotoUrl(c.getString(6));
				ta.setTel(c.getString(7));
				ta.setAddress(c.getString(8));
				ta.setLatitude(c.getDouble(9));
				ta.setLongitude(c.getDouble(10));

				c.close();
			} else {
				c.close();
				return null;
			}
		} catch (Exception e) {
			return null;
		}
		return ta;
	}

	@Override
	public String dbName() {
		return "ta.db";
	}

	@Override
	public File dbDir(Context c) {
		return c.getCacheDir();
	}

}
